/* eslint-disable no-undef */
/* eslint-disable camelcase */
/* eslint-disable one-var */
/* eslint-disable eqeqeq */
/* eslint-disable no-useless-escape */
/* eslint-disable no-extend-native */
import config from './../config'
import request from './request'
Date.prototype.format = function (fmt) {
  var _complete = function (n) {
    return n > 9 ? n : '0' + n
  }
  var year = this.getFullYear()
  var month = _complete(this.getMonth() + 1)
  var day = _complete(this.getDate())
  var hours = _complete(this.getHours())
  var minutes = _complete(this.getMinutes())
  var second = _complete(this.getSeconds())
  var result = fmt
  result = result.replace('yyyy', year)
  result = result.replace('MM', month)
  result = result.replace('dd', day)
  result = result.replace('HH', hours)
  result = result.replace('mm', minutes)
  result = result.replace('ss', second)

  return result
}

// Warn if overriding existing method
if (Array.prototype.equals) {
  console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.")
}
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
  // if the other array is a falsy value, return
  if (!array) {
    return false
  }

  // compare lengths - can save a lot of time
  if (this.length != array.length) {
    return false
  }

  for (var i = 0, l = this.length; i < l; i++) {
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
      // recurse into the nested arrays
      if (!this[i].equals(array[i])) {
        return false
      }
    } else if (this[i] != array[i]) {
      // Warning - two different object instances will never be equal: {x:20} != {x:20}
      return false
    }
  }
  return true
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, 'equals', {
  enumerable: false
})

function formatNumber(n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}
/**
 * {
  count = 9,
  sizeType = ['original', 'compressed'],
  useCamera = false
}
 */
function uploadImage(data = {
  count: 9,
  sizeType: ['original', 'compressed'],
  useCamera: false,
  maxSize: 0
}) {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: data.count,
      sizeType: data.sizeType,
      sourceType: data.useCamera ? ['album', 'camera'] : ['album'],
      success: (result) => {
        console.log('选择了文件')
        console.log(result)

        let file = result.tempFiles[0]
        console.log(file.size)
        // 最大文件大小限制
        if (data.maxSize && file.size > data.maxSize) {
          let maxSize = conver(data.maxSize)
          wxAlert(`文件大小不能超过${maxSize}`)
          return false
        }
        let cookie = wx.getStorageSync('sessionid')
        const user = wx.getStorageSync('currentUser')
        wx.showLoading({
          title: '正在上传...',
          mask: true
        })
        wx.uploadFile({
          url: config.urlHead + 'img/upload',
          header: {
            Accept: '*/*',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cookie': cookie,
            'Content-Type': 'multipart/form-data;',
            Connection: 'keep-alive',
            'X-Requested-With': 'XMLHttpRequest'
          },
          filePath: result.tempFilePaths[0],
          name: 'files',
          formData: {
            type: 0,
            userId: user.id
          },
          success: (result) => {
            console.log(result)
            wx.hideLoading()
            resolve(JSON.parse(result.data))
          },
          fail: (err) => {
            reject(err)
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

function wxLoading(title = '加载中...', mask = true) {
  wx.showLoading({
    title,
    mask
  })
}
/**
 * 要跳转到某一页
 * @param {String} url 要跳转的路径
 */
function routerTo(url) {
  wx.showLoading({
    title: '正在跳转...',
    mask: true
  })
  wx.navigateTo({
    url,
    complete: () => {
      setTimeout(() => wx.hideLoading(), 2000)
    }
  })
}

/**
 * 关闭当前页面并跳转到某一页
 * @param {String} url 要跳转的路径
 */
function placeTo(url) {
  wx.showLoading({
    title: '正在跳转...',
    mask: true
  })
  wx.redirectTo({
    url,
    complete: () => {
      setTimeout(() => wx.hideLoading(), 2000)
    }
  })
}

function getCurrentPage() {
  var pages = getCurrentPages() // eslint-disable-line no-undef
  return pages
}
/**
 * 返回上一页
 * @param {*} delta 返回上一页
 */
function routerBack(delta = 1) {
  wx.navigateBack({
    delta
  })
}

/**
 * 统一验证结果
 * @param {*} obj 要验证的对象
 */
function commonValidate(obj) {
  for (var key in obj) {
    let value = obj[key]
    // console.log(value)
    if (value.toString().trim() !== '') {
      return false
    }
  }
  return true
}
/**
 * 创建API
 * @param {String} api 上下文对象
 * @param {String} name api名称
 * @param {String} url api地址
 * @param {*} data 参数
 * @param {String} method 提交方式 get post put delete
 */
function commonAddApi(api, name, url, method) {
  api[name] = ({
    data
  } = {
    data: {}
  }) => request[method](config.urlHead + url, data)
}
/**
 * 把cookie转成json对象
 * @param {String} cookie
 */
function cookiefy(cookie) {
  if (!cookie) return
  let cookies = cookie.split('; ')
  let obj = {}
  cookies.map(item => {
    if (item.startsWith('Expires=')) {
      var tempArr = item.split('=')
      let sessionid = tempArr[2]
      let timeArr = tempArr[1].split(',')
      obj.Expires = `${timeArr[0]}, ${tempArr[1]}`
      obj.CLSYSSESSIONID = sessionid
    } else {
      var arr = item.split('=')
      obj[arr[0]] = arr[1]
    }
  })
  return {
    cookies: obj,
    /**
     * 根据名称获取cookie
     * @param {String} name cookie名称
     */
    getCookieByName(name) {
      return obj[name]
    }
  }
}
/**
 * 调用wx.showModal 弹出提示
 * @param {String} title 标题
 * @param {String} content 内容
 * @param {Function} success 成功回调函数
 */
function wxAlert(content, title, success) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: title || '系统提示',
      content,
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (result) => {
        if (result.confirm) {
          success && success()
          resolve(result)
        }
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {}
    })
  })
}
/**
 * 弹出简要toast信息
 * @param {String} title 信息文字
 * @param {String} icon 弹出图标
 * @param {number} duration 间隔时间
 */
function wxToast(title, icon = 'none', duration = 1000) {
  return new Promise(function (resolve, reject) {
    wx.showToast({
      title,
      icon,
      duration,
      success: resolve
    })
  })
}
/**
 * 弹出toast成功信息
 * @param {String} title 信息文字
 * @param {Function} cb 回掉函数
 */
function wxToastSuccess(title = '操作成功', cb) {
  return new Promise((resolve, reject) => {
    wx.showToast({
      title,
      icon: 'success',
      success: () => {
        cb && cb()
        resolve()
      }
    })
  })
}
/**
 * toast弹出错误信息
 * @param {Stringq} title 失败信息
 * @param {Function} cb 失回掉函数
 */
function wxToastFail(title = '操作失败', cb) {
  wx.showToast({
    title,
    icon: 'none',
    success: () => cb && cb()
  })
}
/**
 * 深拷贝
 * @param {*} obj 西药拷贝的对象
 */
function deepClone(obj) {
  let newObj = obj.push ? [] : {} // 如果obj有push方法则 定义newObj为数组，否则为对象。
  for (let attr in obj) {
    if (typeof obj[attr] === 'object' && obj[attr] !== null) {
      newObj[attr] = deepClone(obj[attr])
    } else {
      newObj[attr] = obj[attr]
    }
  }
  return newObj
}
/**
 * 数字转KB、MB、GB
 * @param {number} limit
 */
function conver(limit) {
  var size = ''
  if (limit < 0.1 * 1024) { // 如果小于0.1KB转化成B
    size = limit.toFixed(2) + 'B'
  } else if (limit < 0.1 * 1024 * 1024) { // 如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + 'KB'
  } else if (limit < 0.1 * 1024 * 1024 * 1024) { // 如果小于0.1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
  } else { // 其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }

  var sizestr = size + ''
  var len = sizestr.indexOf('\.')
  var dec = sizestr.substr(len + 1, 2)
  if (dec == '00') { // 当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
  }
  return sizestr
}
/**
 * 根据key过滤对象属性
 * @param {*} obj
 * @param {String} keys 键值
 */
function filtObjectByKeys(obj = {}, keys = []) {
  var o = {}
  Object.keys(obj).map((key) => {
    if (keys.includes(key)) o[key] = obj[key]
  })
  return o
}

/**
 * 产生任意长度随机字母数字组合
 * @param {Object} randomFlag 是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
 * @param {Object} min 最小长度
 * @param {Object} max 最大长度
 * @return {String} 随机字符串
 */
function randomWord(randomFlag, min, max) {
  var str = '',
    range = min,
    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min
  }
  for (var i = 0; i < range; i++) {
    let pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[pos]
  }
  return str
}
/**
 * 合并对象并排空
 */
function assignWithoutNull() {
  if (!arguments.length) return {}
  let arg0 = arguments[0]
  for (let i = 1; i < arguments.length; i++) {
    let item = arguments[i]
    if (Object.prototype.toString.call(item) !== '[object Object]') continue
    Object.keys(item).map(key => {
      if (item[key] !== null) arg0[key] = item[key]
    })
  }
  return arg0
}
// 经纬度转换成三角函数中度分表形式。
function rad(d) {
  return d * Math.PI / 180.0
}

/**
 * 计算两个经纬度之间的距离 单位为千米
 * @param {Number} lat1 第一个点的纬度
 * @param {Number} lng1 第一个点的经度
 * @param {Number} lat2 第二个点的纬度
 * @param {Number} lng2 第二个点的经度
 */
function getDistance(lat1, lng1, lat2, lng2) {
  var radLat1 = rad(lat1)
  var radLat2 = rad(lat2)
  var a = radLat1 - radLat2
  var b = rad(lng1) - rad(lng2)
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
  s = s * 6378.137 // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000 // 输出为公里

  var distance = s
  var distance_str = ''

  if (parseInt(distance) >= 1) {
    distance_str = distance.toFixed(1) + 'km'
  } else {
    distance_str = distance * 1000 + 'm'
  }

  // s=s.toFixed(4);

  // console.info('lyj 距离是', s);
  // console.info('lyj 距离是', distance_str);
  return distance_str
}
/**
 * @Description 过滤掉字符串中的特殊字符
 * @author 孙畅
 * @date 2020-10-15
 * @param {String} str
 * @returns {String}
 */
function filtString(str) {
  // 将名称拆分为数组,注意: 这样会将表情拆分为两项,其值为代理对.

  // 并且因为,代理对无法被浏览器识别,所以它们的值可能会被转化为 U+feff

  var strArr = str.split(''),
    result = '',
    totalLen = 0

  for (var idx = 0; idx < strArr.length; idx++) {
    // 超出长度,退出程序

    if (totalLen >= 16) break

    var val = strArr[idx]

    // 英文,增加长度1

    if (/[a-zA-Z]/.test(val)) {
      totalLen = 1 + (+totalLen)

      result += val
    } else if (/[\u4e00-\u9fa5]/.test(val)) {
      totalLen = 2 + (+totalLen)

      result += val
    } else if (/[\ud800-\udfff]/.test(val)) {
      // 遇到代理字符,将其转换为 "口", 不增加长度
      // 代理对长度为2,
      if (/[\ud800-\udfff]/.test(strArr[idx + 1])) {
        // 跳过下一个
        idx++
      }
      // 将代理对替换为 "口"
      result += '口'
    }
  }
  return result
}
export default {
  getDistance,
  assignWithoutNull,
  uploadImage,
  getCurrentPage,
  formatNumber,
  formatTime,
  commonValidate,
  routerBack,
  routerTo,
  placeTo,
  commonAddApi,
  cookiefy,
  wxAlert,
  wxLoading,
  wxToast,
  wxToastSuccess,
  wxToastFail,
  deepClone,
  conver,
  filtObjectByKeys,
  randomWord,
  filtString
}
